/**
 * 
 * @param pickBtn               选取按钮
 * @param showList
 * @param fileSingleSizeLimit   文件大小，int
 * @param fileNumLimit          文件数量
 * @param extensions            扩展名，gif，jpg
 * @param mimeTypes             类型，image/gif
 * @type                        文件类型
 * @return
 */
function initFileUploader(pickBtn, showList, fileSingleSizeLimit, fileNumLimit, extensions, mimeTypes, type) {
	var BASE_URL = "/lib/webuploader";
	var $list = $("#" + showList);
	var state = "pending";
	
	var uploader = WebUploader.create({
		auto: true,
	    swf: BASE_URL + '/Uploader.swf',
	    server: '/_upload',
	    pick: '#' + pickBtn,
	    resize: false,
	    fileVal: "file",
	    fileNumLimit: fileNumLimit,
	    fileSingleSizeLimit: fileSingleSizeLimit,
	    compress: false,
	    accept: {
	        title: 'file',
	        extensions: extensions,
	        mimeTypes: mimeTypes
	    }
	});
	// 当有文件被添加进队列的时候
	uploader.on( 'fileQueued', function( file ) {
	    $list.append( 
			'<dd id="' + file.id + '" class="item">' +
	    	'<div class="removeFileListener delete"><span>删除</span></div>' +
	        '<div class="info">' + file.name + "(" + Math.round(file.size / 1024) + "kb) -100%" + '</div>' +
	        '<div class="state">等待上传...</div>' +
	    	'</dd>'
		 );
	});
	// 文件上传过程中创建进度条实时显示。
	uploader.on( 'uploadProgress', function( file, percentage ) {
	    var $li = $( '#'+file.id ),
	        $percent = $li.find('.progress .progress-bar');

	    // 避免重复创建
	    if ( !$percent.length ) {
	        $percent = $('<div class="progress progress-striped active">' +
	        '<div class="progress-bar" role="progressbar" style="width: 0%"></div>' +
	        '</div>').appendTo( $li ).find('.progress-bar');
	    }

	    $li.find('div.state').text('上传中');

	    $percent.css( 'width', percentage * 100 + '%' );
	});

	uploader.on( 'uploadSuccess', function( file, response ) {
	    $( '#'+file.id ).find('div.state').text('已上传');
        $( '.lib_batchOk_btn' ).show();
	    $( '#'+file.id ).append('<input type="hidden" name="'+  type +'" value="'+ response._raw +'" />');
		setTimeout(function () {
			$('#'+file.id ).find('div.state').fadeOut();
		}, 500);
	});
	
	uploader.on( 'uploadError', function( file ) {
	    $( '#'+file.id ).find('div.error').text('上传出错');
	});
	
	uploader.on( 'uploadComplete', function( file ) {
	    $( '#'+file.id ).find('.progress').fadeOut();
	    $(".removeFileListener").on("click", function(){
	    	removeUploadFile(uploader, $(this));
            $( '.lib_batchOk_btn' ).hide();
		});
	});

	uploader.on( 'error', function( type ) {
		
	    if (type == "Q_EXCEED_NUM_LIMIT") {
			alert("上传的文件数量不能超过" + fileNumLimit);
	    } else if (type == "Q_EXCEED_SIZE_LIMIT") {
			alert("上传的文件大小不能超过" + fileSingleSizeLimit + "字节");
	    } else if (type ==  "Q_TYPE_DENIED") {
			alert("不支持这种文件类型");
	    } else if (type == "F_EXCEED_SIZE") {
	    	alert("上传的文件大小不能超过" + fileSingleSizeLimit + "字节");
	    } else if (type == "F_DUPLICATE") {
			alert("已经上传过了");
	    } else {
	    	alert(type);
	    }
	});
	
    $(".removeFileListener").on("click", function(){
    	removeUploadFile(uploader, $(this));
	});
}


/**
 * 
 * @param pickBtn               选取按钮
 * @param uploadBtn             上传按钮
 * @param showList
 * @param fileSingleSizeLimit   文件大小，int
 * @param fileNumLimit          文件数量
 * @param extensions            扩展名，gif，jpg
 * @param mimeTypes             类型，image/gif
 * @param type                  文件类型
 * @return
 */
function initImageUploader(pickBtn, showList, fileSingleSizeLimit, fileNumLimit, extensions, mimeTypes, type, callback) {
	var $pickBtn = $("#" + pickBtn);
	var BASE_URL = "/lib/webuploader";
	var $list = $("#" + showList);
	var state = "pending";
	var thumbnailWidth = 120;
	var thumbnailHeight = 120;
	
	var uploader = WebUploader.create({
		auto: true,
	    swf: BASE_URL + '/Uploader.swf',
	    server: '/_upload',
	    pick: '#' + pickBtn,
	    resize: false,
	    fileVal: "file",
	    fileNumLimit: fileNumLimit,
	    fileSingleSizeLimit: fileSingleSizeLimit,
	    compress: false,
	    accept: {
	        title: 'file',
	        extensions: extensions,
	        mimeTypes: mimeTypes
	    }
	});
	
	// 当有文件被添加进队列的时候
	uploader.on( 'fileQueued', function( file ) {
		var imgName = file.name;
		$pickBtn.attr("value",imgName);
		var $li = $(
	            '<dd id="' + file.id + '" class="file-item thumbnail" mouseenter="">' +
					'<div class="file-panel">' +
						'<span class="editor" style="display:none;">编辑</span>' +
						'<span class="removeFileListener delete">删除</span>' +
						'<span class="rotateRight">向右旋转</span>' +
						'<span class="rotateLeft">向左旋转</span>' +
					'</div>' +
	                '<div class="imgWrap"><p><img></p></div>' +
	                '<div class="info" title="' + file.name + '">' + file.name + '</div>' +
	            '</dd>'
            ),
            $img = $li.find('img');
	    // $list为容器jQuery实例
	    $list.append( $li );

	    // 创建缩略图
	    // 如果为非图片文件，可以不用调用此方法。
	    // thumbnailWidth x thumbnailHeight 为 100 x 100
	    uploader.makeThumb( file, function( error, src ) {
	        if ( error ) {
	            $img.replaceWith('<span>不能预览</span>');
	            return;
	        }

	        $img.attr( 'src', src );
	    }, thumbnailWidth, thumbnailHeight );
	});
	
	// 文件上传过程中创建进度条实时显示。
	uploader.on( 'uploadProgress', function( file, percentage ) {
		var $li = $('#' + file.id),
        $percent = $li.find('.progress span');
	    // 避免重复创建
	    if ( !$percent.length ) {
	        $percent = $('<p class="progress"><span></span></p>').appendTo( $li ).find('span');
	    }
	    $percent.css( 'width', percentage * 100 + '%' );
	});

	uploader.on( 'uploadSuccess', function( file, response ) {
		$( '#'+file.id ).addClass('upload-state-done');
		$( '#'+file.id ).append('<input type="hidden" name="' + type + '" value="' + response._raw + '" />');

		if(callback){
			callback(showList);
		}
	});
	
	uploader.on( 'uploadError', function( file ) {
		var $li = $( '#'+file.id ),
        $error = $li.find('div.error');

	    // 避免重复创建
	    if ( !$error.length ) {
	        $error = $('<div class="error"></div>').appendTo( $li );
	    }
	
	    $error.text('上传失败');
	});
	
	uploader.on( 'uploadComplete', function( file ) {
		$( '#'+file.id ).find('.progress').remove();
	});

	uploader.on( 'error', function( type ) {
	    if (type == "Q_EXCEED_NUM_LIMIT") {
			alert("上传的文件数量不能超过" + fileNumLimit);
	    } else if (type == "Q_EXCEED_SIZE_LIMIT") {
	    	alert("上传的文件大小不能超过" + fileSingleSizeLimit/1024 + "kb");
	    } else if (type ==  "Q_TYPE_DENIED") {
			alert("不支持这种文件类型");
	    } else if (type == "F_EXCEED_SIZE") {
	    	alert("上传的文件大小不能超过" + fileSingleSizeLimit/1024 + "kb");
	    } else if (type == "F_DUPLICATE") {
			alert("已经上传过了");
	    } else {
	    	alert(type);
	    }
	});
	
	$("dl.uploader-img-list").on("click", '.removeFileListener', function(){
	    removeUploadFile(uploader, $(this));
	});
	
	// 为dd添加hover效果 显示功能按钮
	$("dl.uploader-img-list").on("mouseenter", 'dd', function(){
	    $(this).find(".file-panel").slideDown()
		$(this).find(".info").slideDown()
	});
	
	$("dl.uploader-img-list").on("mouseleave", 'dd', function(){
		$(this).find(".file-panel").slideUp()
		$(this).find(".info").slideUp()
	});
	 
}
	
function removeUploadFile(uploader, obj) {
	var parentObj = obj.closest("dd");
	var id = parentObj.attr("id");
	
	try {
		//被上传控件托管，还没有进入annex，直接删除文件即可
		parentObj.remove();
		uploader.removeFile(id, true); 
		//物理删除
		var filePath = parentObj.find("input").val();
		filePath = filePath.substring(0, filePath.indexOf("|"));
		
		jQuery.ajax({
			type:'',
			dataType:'text',
			url: '/deleteFile',
			data: 'filePath=' + filePath + '&t=' + new Date().getTime(),
			success:function(data){
				
			}
		});
	} catch (e){
		//不在上传控件中托管，已进入annex,需要删除annex
		jQuery.ajax({
			type:'',
			dataType:'text',
			url: '/deleteFile',
			data: 'annexId=' + id + '&t=' + new Date().getTime(),
			success:function(data){
				
			}
		});
	}
}

//编辑页面图片处理
function picture_ready (obj, field) {
    var html = '';
    var _this = $("#" + field);
    if (obj && obj.indexOf(",") != -1) {
    	//多图
        var pictures_arr = obj.split(",");
        for (var i = 0; i < pictures_arr.length; i++) {
            var name = pictures_arr[i].substring( pictures_arr[i].indexOf("|") + 1);
            var img_url = "";
            if(pictures_arr[i].indexOf("|") != -1) {
                img_url = pictures_arr[i].substring(0,  pictures_arr[i].indexOf("|"));
			} else {
                img_url = pictures_arr[i];
			}
            var type = field.substring(0, field.indexOf('List'));
            html += picture_html(name, img_url, type);
        }
        _this.html(html);
        _this.find("dd").show();
	} else if (obj) {
        var name = obj.substring(obj.indexOf("|") + 1);

        var img_url = "";
        if(obj.indexOf("|") != -1) {
            img_url = obj.substring(0,  obj.indexOf("|"));
        } else {
            img_url = obj;
        }
        var type = field.substring(0, field.indexOf('List'));
        html += picture_html(name, img_url, type);
        _this.html(html);
        _this.find("dd").show();
    }
}

//编辑页面图片处理
function picture_ready2 (obj, field,w,h) {
	var html = '';
	var _this = $("#" + field);
	if (obj && obj.indexOf(",") != -1) {
		//多图
		var pictures_arr = obj.split(",");
		for (var i = 0; i < pictures_arr.length; i++) {
			var name = pictures_arr[i].substring( pictures_arr[i].indexOf("|") + 1);
			var img_url = "";
			if(pictures_arr[i].indexOf("|") != -1) {
				img_url = pictures_arr[i].substring(0,  pictures_arr[i].indexOf("|"));
			} else {
				img_url = pictures_arr[i];
			}
			var type = field.substring(0, field.indexOf('List'));
			html += picture_html2(name, img_url, type,w,h);
		}
		_this.html(html);
		_this.find("dd").show();
	} else if (obj) {
		var name = obj.substring(obj.indexOf("|") + 1);

		var img_url = "";
		if(obj.indexOf("|") != -1) {
			img_url = obj.substring(0,  obj.indexOf("|"));
		} else {
			img_url = obj;
		}
		var type = field.substring(0, field.indexOf('List'));
		html += picture_html2(name, img_url, type,w,h);
		_this.html(html);
		_this.find("dd").show();
	}
}

function picture_html(name, img_url, type){
	var html = 	'<dd class="file-item thumbnail" style="display:none;">' +
				'	<div class="file-panel">' +
				'		<span class="removeFileListener delete">删除</span>' +
				'	</div>' +
				'	<div class="imgWrap">' +
				'		<p>' +
				'			<img src="'+ img_url +'">' +
				'			</p>' +
				'		</div>' +
				'	<div class="info" title="'+ name +'">'+ name +'</div>' +
				'	<input type="hidden" id="'+ type +'" name="'+ type +'" value="'+ img_url + '|'+ name+'" />' +
				'</dd>';
	return html;
}
function picture_html2(name, img_url, type,w,h){
	var html = 	'<dd class="file-item thumbnail" style="display:none;">' +
		'	<div class="file-panel" style="width: '+w+'">' +
		'		<span class="removeFileListener delete">删除</span>' +
		'	</div>' +
		'	<div class="">' +
		'		<p>' +
		'			<img width="'+ w + '"  height="'+ h + '" src="'+ img_url +'">' +
		'			</p>' +
		'		</div>' +
		'	<div class="info" title="'+ name +'" style="width: '+w+'">'+ name +'</div>' +
		'	<input type="hidden" id="'+ type +'" name="'+ type +'" value="'+ img_url + '"/>' +
		'</dd>';
	return html;
}

//编辑页面文件处理
function file_ready (obj, field) {
    var html = '';
    var _this = $("#" + field);
    if (obj && obj.indexOf(",") != -1) {
        var files_arr = obj.split(";");
        for (var i = 0; i < files_arr.length; i++) {
            var name = files_arr[i].substring( files_arr[i].indexOf("|") + 1);
             var file_url = "";
            if( files_arr[i].indexOf("|") != -1) {
                file_url =  files_arr[i].substring(0,  files_arr[i].indexOf("|"));
            } else {
                file_url =  files_arr[i];
            }

            var type = field.substring(0, field.indexOf('List'));
            html += file_html(name, file_url, 1024, type);
        }
        _this.html(html);
    } else if (obj) {
        var name = obj.substring(obj.indexOf("|") + 1);
        var file_url = "";
        if(obj.indexOf("|") != -1) {
            file_url = obj.substring(0, obj.indexOf("|"));
        } else {
            file_url = obj;
        }
        var type = field.substring(0, field.indexOf('List'));
        html += file_html(name, file_url, 1024, type);
        _this.html(html);
    }
}

function file_html(name, file_url, size, type){
    var html = 	'<dd class="item">'+
 				'		<div class="removeFileListener delete"><span>删除</span></div>'+
				'		<h4 class="info">'+ name +'('+ size +'kb)</h4>'+
				'		<input type="hidden" id="'+ type +'" name="'+ type +'" value="'+ file_url + '|'+ name+'" />'+
				'</dd>';
    return html;
}

//图片处理
function picture_show (obj, field,width,height,fileType) {
    var html = '';
    var _this = $("#" + field);
    var w,h;
    width?w=width:w="120px";
    height?h=height:h="120px";
    if (obj && obj.indexOf(",") != -1) {
        //多图
        var pictures_arr = obj.split(",");
        for (var i = 0; i < pictures_arr.length; i++) {
            var name = pictures_arr[i].substring( pictures_arr[i].indexOf("|") + 1);
            var img_url = "";
            if(pictures_arr[i].indexOf("|") != -1) {
                img_url = pictures_arr[i].substring(0,  pictures_arr[i].indexOf("|"));
            } else {
                img_url = pictures_arr[i];
            }
            html += "<a href='" + img_url + "' target='_blank' style='padding-right: 8px' typeInfo='"+fileType+"'><img width='"+w+"' height='"+h+"' src='" + img_url + "'/></a>";
        }
        _this.html(html);
        _this.find("dd").show();
    } else if (obj) {
        var name = obj.substring(obj.indexOf("|") + 1);

        var img_url = "";
        if(obj.indexOf("|") != -1) {
            img_url = obj.substring(0,  obj.indexOf("|"));
        } else {
            img_url = obj;
        }
        html += "<a class='table_row_handle' href='" + img_url + "' target='_blank' style='padding-right: 8px;padding-left: 0px' typeInfo='"+fileType+"'>";
		if(img_url.substr(img_url.length-3,3) == "pdf"){
			html+= name;
		}
		else{
			html += "<img width='"+w+"' height='"+h+"'src='" + img_url + "'>"
		}
		html += "</a>";
        _this.html(html);
        _this.find("dd").show();
    }
}


//复核和个人信息修改图片处理
function picture_show_update (obj, field,width,height,fileType) {
    var html = '';
    var _this = $("#" + field);
    var w,h;
    width?w=width:w="120px";
    height?h=height:h="120px";
    if (obj && obj.indexOf(",") != -1) {
        //多图
        var pictures_arr = obj.split(",");
        for (var i = 0; i < pictures_arr.length; i++) {
            var name = pictures_arr[i].substring( pictures_arr[i].indexOf("|") + 1);
            var img_url = "";
            if(pictures_arr[i].indexOf("|") != -1) {
                img_url = pictures_arr[i].substring(0,  pictures_arr[i].indexOf("|"));
            } else {
                img_url = pictures_arr[i];
            }
            html += "<a href='" + img_url + "' target='_blank' style='padding-right: 8px' typeInfo='"+fileType+"'><img width='"+w+"' height='"+h+"' src='" + img_url + "'/></a>";
        }
        _this.html(html);
        _this.find("dd").show();
    } else if (obj) {
        var name = obj.substring(obj.indexOf("|") + 1);

        var img_url = "";
        if(obj.indexOf("|") != -1) {
            img_url = obj.substring(0,  obj.indexOf("|"));
        } else {
            img_url = obj;
        }
        html += "<a class='table_row_handle' href='" + img_url + "' target='_blank' style='padding-right: 8px;padding-left: 0px' typeInfo='"+fileType+"'>";
        if(img_url.substr(img_url.length-3,3) == "pdf"){
            html+= name;
        }
        else{
            html += "<img width='"+w+"' height='"+h+"'src='" + img_url + "'>"
        }
        html += "</a>";
        _this.html(html);
        _this.find("dd").show();
    } else {
        html += "<a class='table_row_handle' href='javascript:void(0);' style='padding-right: 8px;padding-left: 0px' typeInfo='"+fileType+"'>";
        html += "<img width='"+w+"' height='"+h+"' src='/admin/images/nopic-1.png'>";
        html += "</a>";
        _this.html(html);
        _this.find("dd").show();
	}
}


/**
 *
 * @param pickBtn               选取按钮
 * @param showList
 * @param fileSingleSizeLimit   文件大小，int
 * @param fileNumLimit          文件数量
 * @param extensions            扩展名，gif，jpg
 * @param mimeTypes             类型，image/gif
 * @type                        文件类型
 * @return
 */
function initFileUploaderBox(pickBtn, showList, fileSingleSizeLimit, fileNumLimit, extensions, mimeTypes, type) {
    var BASE_URL = "/jslib/webuploader";
    var $list = $("#" + showList);
    var state = "pending";

    var uploader = WebUploader.create({
        auto: true,
        swf: BASE_URL + '/Uploader.swf',
        server: '/_upload',
        pick: '#' + pickBtn,
        resize: false,
        fileVal: "file",
        fileNumLimit: fileNumLimit,
        fileSingleSizeLimit: fileSingleSizeLimit,
        compress: false,
        accept: {
            title: 'file',
            extensions: extensions,
            mimeTypes: mimeTypes
        }
    });
    // 当有文件被添加进队列的时候
    uploader.on( 'fileQueued', function( file ) {
        $list.append(
            '<dd id="' + file.id + '" class="item">' +
            '<div class="removeFileListener delete"><span>删除</span></div>' +
            '<div class="info">' + file.name +"("+ Math.round(file.size / 1024) +"kb) -100%"+ '</div>' +
            '<div class="state">等待上传...</div>' +
            '</dd>'
        );
    });
    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');

        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('div.state').text('上传中');

        $percent.css( 'width', percentage * 100 + '%' );
    });

    uploader.on( 'uploadSuccess', function( file, response ) {
        $( '#'+file.id ).find('div.state').text('已上传');
        $( '#'+file.id ).append('<input type="hidden" name="'+  type +'" value="'+ response._raw +'" />');
        setTimeout(function () {
            $('#'+file.id ).find('div.state').fadeOut();
        }, 500);
    });

    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('div.error').text('上传出错');
    });

    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
        $(".removeFileListener").on("click", function(){
            removeUploadFile(uploader, $(this));
        });
    });

    uploader.on( 'error', function( type ) {

        if (type == "Q_EXCEED_NUM_LIMIT") {
            alertBox("上传的文件数量不能超过" + fileNumLimit);
        } else if (type == "Q_EXCEED_SIZE_LIMIT") {
            alertBox("上传的文件大小不能超过" + fileSingleSizeLimit + "字节");
        } else if (type ==  "Q_TYPE_DENIED") {
            alertBox("不支持这种文件类型");
        } else if (type == "F_EXCEED_SIZE") {
            alertBox("上传的文件大小不能超过" + fileSingleSizeLimit + "字节");
        } else if (type == "F_DUPLICATE") {
            alertBox("已经上传过了");
        } else {
            alertBox(type);
        }
    });

    $(".removeFileListener").on("click", function(){
        removeUploadFile(uploader, $(this));
    });
}
